from django.core.exceptions import ValidationError
from django.shortcuts import render, redirect
from django import forms

from manage_worker import models
from manage_worker.utills.bootsrtap import BootStrapModelForm
from manage_worker.utills.pagination import Pagination
from manage_worker.utills.encrypt import md5


def admin_list(request):
    data_list = {}
    search_data = request.GET.get('q', '')
    if search_data:
        data_list['username__contains'] = search_data
    queryset = models.Admin.objects.filter(**data_list)
    page_object = Pagination(request, queryset=queryset)

    context = {
        'queryset': page_object.page_queryset,
        'page_string': page_object.html(),
        'search_data': search_data
    }

    return render(request, 'admin_list.html', context)


class AdminModelForm(BootStrapModelForm):
    confirm_password = forms.CharField(
        label='确认密码',
        # render_value=True提交失败后不清除输入框
        widget=forms.PasswordInput(render_value=True)
    )

    class Meta:
        model = models.Admin
        fields = ['username', 'password', 'confirm_password']
        # 这里必须是widgets，如果widget不生效
        widgets = {
            'password': forms.PasswordInput(render_value=True)
        }

    def clean_password(self):
        pwd = self.cleaned_data.get('password')
        # 返回什么，以后的字段就保存什么
        return md5(pwd)

    def clean_confirm_password(self):
        pwd = self.cleaned_data.get('password')
        confirm = md5(self.cleaned_data.get('confirm_password'))
        if pwd != confirm:
            raise ValidationError('密码不一致')
        # 返回什么，以后的字段就保存什么
        return confirm


class AdminEditModelForm(BootStrapModelForm):
    class Meta:
        model = models.Admin
        fields = ['username']


class AdminResetModelForm(BootStrapModelForm):
    confirm_password = forms.CharField(
        label='确认密码',
        # render_value=True提交失败后不清除输入框
        widget=forms.PasswordInput(render_value=True)
    )
    class Meta:
        model = models.Admin
        fields = ['password', 'confirm_password']
        # 这里必须是widgets，如果widget不生效
        widgets = {
            'password': forms.PasswordInput(render_value=True)
        }

    def clean_password(self):
        pwd = self.cleaned_data.get('password')
        md5_pwd = md5(pwd)

        # 两种方法实现查询不能与之前密码一致的功能，
        # 第一种，老师讲的,exists判断此条件的数据是否存在，存在返回True，不存在返回False
        exists = models.Admin.objects.filter(id=self.instance.pk, password=md5_pwd).exists()
        if exists:
            raise ValidationError('不能和之前的密码一致')

        #第二种，自己试的
        # exists = models.Admin.objects.filter(id=self.instance.pk).first()
        # if md5_pwd == exists.password:
        #     raise ValidationError('不能和之前的密码一致')
        # 返回什么，以后的字段就保存什么
        return md5_pwd

    def clean_confirm_password(self):
        pwd = self.cleaned_data.get('password')
        confirm = md5(self.cleaned_data.get('confirm_password'))
        if pwd != confirm:
            raise ValidationError('密码不一致')
        # 返回什么，以后的字段就保存什么
        return confirm

def admin_add(request):
    title = '添加管理员'
    if request.method == 'GET':
        form = AdminModelForm()
        return render(request, 'change.html', {'form': form, 'title': title})
    form = AdminModelForm(data=request.POST)
    if form.is_valid():
        # print(form.cleaned_data)
        form.save()
        return redirect('/admin/list/')
    return render(request, 'change.html', {'form': form, 'title': title})


def admin_edit(request, id):
    row_object = models.Admin.objects.filter(id=id).first()
    if not row_object:
        return render(request, 'error.html', {'msg': '用户名不存在'})
        # return redirect('/admin/list/')
    title = '编辑管理员'
    if request.method == 'GET':
        form = AdminEditModelForm(instance=row_object)
        return render(request, 'change.html', {'form': form, 'title': title})
    form = AdminEditModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return redirect('/admin/list/')
    return render(request, 'change.html', {'title': title})


def admin_delete(request, id):
    models.Admin.objects.filter(id=id).first().delete()
    return redirect('/admin/list/')


def admin_reset(request, id):
    row_object = models.Admin.objects.filter(id=id).first()
    if not row_object:
        return render(request, 'error.html', {'msg': '用户名不存在'})
    title = '重置密码-----{}'.format(row_object.username)
    if request.method == 'GET':
        form = AdminResetModelForm
        return render(request, 'change.html', {'form': form, title: title})
    form = AdminResetModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return redirect('/admin/list/')
    return render(request, 'change.html', {'form': form, title: title})